package com.wandian.texas.demo;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.BlockingQueue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.ThreadFactory;
import java.util.concurrent.TimeUnit;
import com.wandian.executor.SimpleThreadFactory;
import com.wandian.executor.TimerMgr;
import com.wandian.util.Log;

/**
 * 使用阻塞队列的实现篮子生产消费模型
 * 
 * @author long
 * @Create 2012-10-9 下午12:38:37
 * @QQ 108232706
 * @version 1.0
 * @description BlockingQueueTest
 */
public class BlockingQueueTest {
	public static class Basket {
		// 篮子,能够容纳3个苹果
		BlockingQueue<String> basket = new ArrayBlockingQueue<String>(3);

		// 生产苹果,放入篮子
		public void produce(long time) throws InterruptedException {
			// put方法放入一个苹果,若basket满了,等到basket有位置
			basket.put("Apple" + time);
		}

		// 消费苹果,从篮子中取走
		public String consume() throws InterruptedException {
			// take方法取出一个苹果,若basket为空,等到basket有苹果为止
			return basket.take();
		}
	}

	// final static Basket basket = new Basket();
	// 测试方法
	public static void testBasket() {
		final Basket basket = new Basket();// 建立一个装苹果的篮子

		// 定义苹果生产者
		class Producer implements Runnable {

			public void run() {
				long time;
				try {
					while (true) {
						// 生产苹果
						time = System.currentTimeMillis();
						System.out.println("生产者准备生产苹果: Apple" + time);
						basket.produce(time);
						System.out.println("生产者生产苹果完毕: apple" + time);
						// 休眠300ms
						Thread.sleep(300);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		// 定义苹果消费者

		class Consumer implements Runnable {

			public void run() {

				try {
					long time;
					String apple;
					while (true) {
						// 消费苹果
						time = System.currentTimeMillis();
						System.out.println("消费者准备消费苹果: ");
						apple = basket.consume();
						System.out.println("消费者消费苹果完毕:  " + apple);
						// 休眠1000ms
						Thread.sleep(1000);
					}
				} catch (InterruptedException ex) {

				}
			}

		}
		ExecutorService service = Executors.newCachedThreadPool();
		Producer producer = new Producer();
		Consumer consumer = new Consumer();
		service.submit(producer);
		service.submit(consumer);

		// 程序运行5s后,所有任务停止
		try {

			Thread.sleep(5000);

		} catch (InterruptedException ex) {

		}

		service.shutdownNow();
	}

	public static void testSchedule() {
		class MyThreadFactory implements ThreadFactory, Thread.UncaughtExceptionHandler {
			private final boolean daemon;
			private final String threadName;

			public MyThreadFactory(String threadName, boolean daemon)
			{
				this.threadName = threadName;
				this.daemon = daemon;
			}

			public Thread newThread(Runnable r) {
				Thread t = new Thread(r, this.threadName);
				t.setDaemon(this.daemon);
				t.setUncaughtExceptionHandler(this);
				return t;
			}

			public void uncaughtException(Thread thread, Throwable throwable) {
				Log.error("Uncaught Exception in thread " + thread.getName(), throwable);
			}
		}

		final Basket basket = new Basket();// 建立一个装苹果的篮子

		// 定义苹果生产者
		class Producer implements Runnable {

			public void run() {

				try {
					long time;
					while (true) {
						// 生产苹果
						time = System.currentTimeMillis();
						System.out.println("生产者准备生产苹果: Apple" + time);
						basket.produce(time);
						System.out.println("生产者生产苹果完毕:Apple" + time);
						// 休眠300ms
						Thread.sleep(300);
					}
				} catch (InterruptedException e) {
					e.printStackTrace();
				}
			}
		}

		// 定义苹果消费者

		class Consumer implements Runnable {

			public void run() {

				try {

					String apple;
					while (true) {
						// 消费苹果
						System.out.println("消费者准备消费苹果: ");
						apple = basket.consume();
						System.out.println("消费者消费苹果完毕: " + apple);
						// 休眠1000ms
						Thread.sleep(1000);
					}
				} catch (InterruptedException ex) {

				}
			}

		}
		ScheduledExecutorService service = Executors.newScheduledThreadPool(3, new MyThreadFactory("testMyThreadFactory", false));// 创建3个线程的池
		Producer producer = new Producer();
		Consumer consumer = new Consumer();
		service.execute(producer);
		service.execute(consumer);
		// 程序运行5s后,所有任务停止
		try {

			Thread.sleep(5000);

		} catch (InterruptedException ex) {

		}
		service.shutdownNow();
	}

	static class SimpleRunnable implements Runnable {
		String name;

		public SimpleRunnable(String _name) {
			name = _name;
		}

		short count = 0;

		public void run() {
			count++;
			System.out.println(name + ":" + count);
		}
	}

	public static void testScheduledThreadPoolExecutor() {

		final ScheduledExecutorService service = Executors.newScheduledThreadPool(1, new SimpleThreadFactory("ScheduledExecutorService", false));

		final Runnable beeper1 = new SimpleRunnable("SimpleRunnable1");
		final Runnable beeper2 = new SimpleRunnable("SimpleRunnable2");
		final Runnable beeper4 = new SimpleRunnable("SimpleRunnable4");
		// scheduleAtFixedRate指定周期执行命令
		final ScheduledFuture<?> beeperHandle1 = service.scheduleAtFixedRate(beeper1, 1, 1, TimeUnit.SECONDS);
		final ScheduledFuture<?> beeperHandle2 = service.scheduleAtFixedRate(beeper2, 1, 1, TimeUnit.SECONDS);
		final ScheduledFuture<?> beeperHandle3 = service.schedule(beeper2, 5, TimeUnit.SECONDS);
		final ScheduledFuture<?> beeperHandle4 = service.schedule(beeper4, 5, TimeUnit.SECONDS);
		service.schedule(new Runnable() {
			public void run() {
				System.out.println("10秒时间到，beeperHandle结束了任务");
				beeperHandle1.cancel(true);
				beeperHandle2.cancel(true);
				if (beeperHandle3 != null) {
					System.out.println("beeperHandle3 not null: delay " + beeperHandle3.getDelay(TimeUnit.SECONDS) + " isCancelled " + beeperHandle3.isCancelled() + " isDone "
							+ beeperHandle3.isDone());
					// 任务已经完成，在去尝试终止，返回false
					System.out.println(beeperHandle3.cancel(true));
				}
				if (beeperHandle4 != null) {
					System.out.println("beeperHandle4 not null: delay " + beeperHandle4.getDelay(TimeUnit.SECONDS) + " isCancelled " + beeperHandle4.isCancelled() + " isDone "
							+ beeperHandle4.isDone());
					System.out.println(beeperHandle4.cancel(true));

				}
				service.shutdownNow();
			}
		}, 7, TimeUnit.SECONDS);

		System.out.println("bye");
	}

	public static void testTimerMfr() {
		if (TimerMgr.init(10)) {
			Runnable beeper1 = new SimpleRunnable("SimpleRunnable1");
			Runnable beeper2 = new SimpleRunnable("SimpleRunnable2");
			Runnable beeper4 = new SimpleRunnable("SimpleRunnable4");
			ScheduledFuture<?> beeper1Future = TimerMgr.push(beeper1, 1, 1);
			TimerMgr.Cancel(beeper1Future, 3);
			TimerMgr.push(beeper2, 1, 1);
			TimerMgr.push(beeper2, 5);
			TimerMgr.push(beeper4, 5);
			TimerMgr.shutdown(8);
			// TimerMgr.push(new Runnable() {
			// public void run() {
			// TimerMgr.shutdown();
			// }
			// }, 7);

			// try {
			// TimerMgr.awaitTermination(7);
			// } catch (InterruptedException e) {
			// e.printStackTrace();
			// }
		}
	}
}
